#!/bin/sh
set -e

# Source debconf library
. /usr/share/debconf/confmodule

port_is_valid() {
    case "$1" in
        '-1') return 0 ;;
        [0-9]*)
            if [ "$1" -le "65535" ] 2>/dev/null
            then
                return 0
            fi
            ;;
    esac
    return 1
}

# Get current value for port (or default)
#   Since the priority is medium, this won't show up by default
db_input medium digits/port || true
db_go
db_get digits/port
PORT="$RET"


if port_is_valid $PORT
then
    PORT_VALID=true
else
    PORT_VALID=false
fi

# loop until we have a valid port, or the same value is entered twice
while [ "$PORT_VALID" = false ]
do
    # Add error messages
    if [ "$PORT_VALID" = false  ]
    then
        db_reset digits/port-invalid
        db_input critical digits/port-invalid || true
    fi

    # Ask for the port
    db_fset digits/port seen false
    db_input critical digits/port || true
    db_go
    db_get digits/port
    NEW_PORT="$RET"

    # Exit if value unchanged
    if [ "$NEW_PORT" = "$PORT" ]
    then
        echo Port unchanged. Aborting.
        exit 1
    fi

    # Recalculate valid/bound
    PORT="$NEW_PORT"
    if port_is_valid $PORT
    then
        PORT_VALID=true
    else
        PORT_VALID=false
    fi
done
